// ==UserScript==
// @name           Beautipedia
// @description    Style for Wikipedia and sister sites, based on style from Beautipedia for Safari
// @include        http://*.wikipedia.*
// @include        https://*.wikipedia.*
// @include        http://*.wikibooks.*
// @include        https://*.wikibooks.*
// @include        http://*.wikiquote.*
// @include        https://*.wikiquote.*
// @include        http://*.wikiversity.*
// @include        https://*.wikiversity.*
// @include        https://*.wikimedia.*
// @include        http://*.wikimedia.*
// @include        https://*.wikisource.*
// @include        http://*.wikisource.*
// @include        http://*.wiktionary.*
// @include        https://*.wiktionary.*
// @include        https://*.secure.wikimedia.*
// @exclude        http://www.wikipedia.org/
// @exclude        https://www.wikipedia.org/
// ==/UserScript==

window.addEventListener('load', function() {

    var path = 'styles/beautipedia.css';

    var style;

    // Error check for the stylesheet filename.
    if (!path) {
        opera.postError('EXTENSION ERROR: No CSS file has been specified');
        return;
    }

    var onCSS = function(event) {
        var message = event.data;

        // Check this is the correct message and path from the background script.
        if (message.topic === 'LoadedInjectedCSS' && message.data.path === path) {
            // Remove the message listener so it doesn't get called again.
            opera.extension.removeEventListener('message', onCSS, false);

			var css = message.data.css;

			// Create a <style> element and add it to the <head> element of the current page.
			// Insert the contents of the stylesheet into the <style> element.
			style = document.createElement('style');
			style.setAttribute('type', 'text/css');
			style.appendChild(document.createTextNode(css));
			document.getElementsByTagName('head')[0].appendChild(style);

			function equivalentURL(countryCode) {
				/*Creates regular expression of country code plus hyphen. sets default link. loops through available language links. if one is found, newLoc is set to it. newLoc is returned. */
				langExp = RegExp("-"+countryCode);
				newLoc = "javascript: alert('This page does not exist (or cannot be accessed) in your chosen language.');";
				ul = document.getElementById("p-lang");
				if (ul) {
					ul = ul.getElementsByTagName("li");
					for (i = 0; i < ul.length; ++i) {
						if (langExp.test(ul[i].getAttribute("class"))) {
							newLoc = ul[i].childNodes[0].getAttribute("href");
						}
					}
					}
				return newLoc;
			}

			function otherLangHref(code){
				var otherLangCode = /http:\/\/en\.|https:\/\/secure.wikimedia.org\/wikipedia\/en\//.test(window.location.href) ? code : "en";
				return equivalentURL(otherLangCode);
			}

			function createLink(text, hrefAttr, classAttr, idAttr) {
				var mlLink = document.createElement("a");
				if (hrefAttr)
					mlLink.setAttribute("href", hrefAttr);
				if (text)
					mlLink.appendChild(document.createTextNode(text));
				if (classAttr)
					mlLink.setAttribute("class", classAttr);
				if (idAttr)
					mlLink.setAttribute("id", idAttr);
				return mlLink
			}

			var mainLink, mlDiv;

			/* Main Link (in upper right corner) */
			mainLink = createLink("W", "http://www.wikipedia.org/wiki/Main_Page", null, "mainLink");
			mlDiv = document.createElement("div");

			/*  Set up links for link box. Each block of text uses the mlLink variable set to a new element. At the end of each block, the element is appended to mlLinksDiv.*/
			function createMenu() {
				var mlLinksDiv = document.createElement("div");
				mlLinksDiv.setAttribute("id", "mlLinksDiv");
				mlLinksDiv.setAttribute("class", (widget.preferences.displayMlLinksDiv=="1"?"mlLinksDivShow":"mlLinksDivHide"));

				mlLinksDiv.appendChild(createLink("Main Page", "http://www.wikipedia.org/wiki/Main_Page"));

				mlLinksDiv.appendChild(createLink("Random Page", "http://www.wikipedia.org/wiki/Special:Random"));

				// Language Switch Button
				var langSwitchHref = otherLangHref(widget.preferences.otherLang);
				var langSwitchEnable = widget.preferences.enableFLS=="1"?"on":"off";
				mlLinksDiv.appendChild(createLink("Switch", langSwitchHref, langSwitchEnable , "fwpLangSwitch"));


				/*	In this if/else statement, the script checks if the userpage link exists (and therefore the user is logged in). If it does, it will add the rest of the user links. Otherwise, it will add a login link. The user links also adds an <hr> element for legibility. */
				if (document.getElementById("pt-userpage")) {
					mlLinksDiv.appendChild(document.createElement("hr"));

					/*User Page*/
					var mlLink = createLink(null, document.getElementById("pt-userpage").childNodes[0].getAttribute("href"));
					mlLink.appendChild(document.createTextNode(document.getElementById("pt-userpage").childNodes[0].childNodes[0].nodeValue));
					mlLinksDiv.appendChild(mlLink);

					mlLinksDiv.appendChild(createLink("Preferences", document.getElementById("pt-preferences").childNodes[0].getAttribute("href")));

					mlLinksDiv.appendChild(createLink("Watchlist", document.getElementById("pt-watchlist").childNodes[0].getAttribute("href")));

					mlLinksDiv.appendChild(createLink("Log Out", document.getElementById("pt-logout").childNodes[0].getAttribute("href")));
				} else {
					mlLinksDiv.appendChild(createLink("Log In", "http://en.wikipedia.org/w/index.php?title=Special:UserLogin"));
				}

				/* This Article Link */
				if (document.getElementById("ca-nstab-main")) {
					mlLinksDiv.appendChild(document.createElement("hr"));
					mlLinksDiv.appendChild(createLink("This Page", document.getElementById("ca-nstab-main").childNodes[0].childNodes[0].getAttribute("href")));
				}

				/*	Edit link, switches between an edit link (if the page can be edited) and a view source link(if the page cannot be edited). Both links will never appear on the same page. If neither appear, it's most likely a special page like Preferences.*/
				mlLink = document.createElement("a");
				if (document.getElementById("ca-edit")) {
					mlLinksDiv.appendChild(createLink("Edit", document.getElementById("ca-edit").childNodes[0].childNodes[0].getAttribute("href")));
				} else if (document.getElementById("ca-viewsource")) {
					mlLinksDiv.appendChild(createLink("View Source", document.getElementById("ca-viewsource").childNodes[0].childNodes[0].getAttribute("href")));
				}

				/* Talk Link */
				if (document.getElementById("ca-talk")) {
					mlLinksDiv.appendChild(createLink("Talk", document.getElementById("ca-talk").childNodes[0].childNodes[0].getAttribute("href")));
				}

				/* History Link */
				if (document.getElementById("ca-history")) {
					mlLinksDiv.appendChild(createLink("History", document.getElementById("ca-history").childNodes[0].childNodes[0].getAttribute("href")));
				}

				return mlLinksDiv;
			}

			mainLink.appendChild(createMenu());

			/* Append "W" to main DIV */
			mlDiv.setAttribute("id", "mlDiv");
			mlDiv.appendChild(mainLink);

			document.body.appendChild(mlDiv);

			/*Fix search menu blurring*/
			var searchInput = document.getElementById('searchInput');
			searchInput.setAttribute("onfocus", "document.getElementById('p-search').setAttribute('class','fwpfocused');");
			searchInput.setAttribute("onblur","document.getElementById('p-search').removeAttribute('class');");

			/*set up link coloring and indent*/
			var attrColor = widget.preferences.colorLinks=="1" ? "fwpColorLinksOn" : "fwpColorLinksOff";
			var attrIndent = widget.preferences.textIndent=="1" ? "fwpIndentOn" : "fwpIndentOff";
			document.getElementById("bodyContent").setAttribute("class", attrColor + " " + attrIndent);

			return true;
        }
		return false;
    }

    // On receipt of a message from the background script, execute onCSS().
    opera.extension.addEventListener('message', onCSS, false);

    // Send the stylesheet path to the background script to get the CSS.
    opera.extension.postMessage({
        topic: 'LoadInjectedCSS',
        data: path
    });

}, false);
